<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/9/29
 * Time: 15:37
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
class Ordercancel extends Base
{
    /**
     * 已支付订单取消后的数据，需要审核
     */
    public function index(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            $map['is_delete'] = 0;
            $map['order_contract'] = ['<>',3];
            if(isset($contract)&&$contract!="")
            {
                $map['order_contract'] = $contract;
            }
            if(isset($n_title)&&$n_title!="")
            {
                $map['order_no|order_back_order_id|name|mobile|express_no|order_cancel_number'] = ['like',"%" . $n_title . "%"];
            }
            if(isset($orderid)&&$orderid!="")
            {
                $map['order_id'] = $orderid;
            }
            if(isset($type) && $type){
                $map['order_push_erp'] = $type;
            }
            if(isset($cancelstatus) && $cancelstatus){
                $map['order_cancel_status'] = $cancelstatus;
            }else{
                $map['order_cancel_status'] = ['>=',2];
            }
            if(isset($paystatus) && $paystatus){
                $map['order_cancel_pay'] = $paystatus;
            }
            //专为退款审核查看
            if(isset($order_master_status)&&$order_master_status!="")
            {
                if($order_master_status == 1){
                    $map['order_master_status'] = ['in','3,4'];
                }else{
                    $map['order_master_status'] = $order_master_status;
                }

            }
            if(isset($start)&&$start!=""&&isset($end)&&$end=="")
            {
                $map['order_cancel_time'] = ['>= time',$start];
            }
            if(isset($end)&&$end!=""&&isset($start)&&$start=="")
            {
                $map['order_cancel_time'] = ['<= time',$end];
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end!="")
            {
                $map['order_cancel_time'] = ['between time',[$start,$end]];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'o.*,user_username,user_phone';
            $count = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->count();// 获取总条数
            $lists = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->order('order_cancel_time DESC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            foreach ($lists as $k => $v){
                $lists[$k]['tytime'] = '-';
                if($v['order_cancel_number'] && $v['order_cancel_status']==3) $lists[$k]['tytime'] = date('Y-m-d H:i:s',substr($v['order_cancel_number'],1,10));
            }
            $money = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->sum('total_price');// 获取总条数
            //----------------------------------------------------------

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists, 'money' => $money]);
        }
        return $this->fetch('ordercancel/index');
    }

    /**
     * 同意
     */
    public function orderYesSend(){
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $tui = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->field('user_id,order_cancel_status,order_cancel_pay')
            ->find();
        if($tui['order_cancel_status'] != 4){
            return json(['code'=>100,'msg'=>'只有待审核的才可以同意']);
        }
        $param  = [
            'order_cancel_status'=>3,
            'order_cancel_pay'=>2,
            'is_pay'=>2,
            'order_cancel_number' => 'T' . time() . rand(1000000,9999999),
            'updated_at'=>$today,
        ];
        $res = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->update($param);
        if($res){
            $title = '取消订单成功通知';
            $content = '由客服检验取消订单没有问题，款项将在7-15个工作日内原路退回您的付款账户。';
            allInNotice($title,$content,4,$tui['user_id'],$order_id,2);
            try{
                $this->Jpush(1, $tui['user_id'], '取消订单成功通知', ['n_id' => $order_id,'type' => 2,'n_type' => 4]);
            }catch(\Exception $e){

            }
            return json(['code'=>200,'msg'=>'成功']);
        }else{
            return json(['code'=>100,'msg'=>'失败']);
        }
    }
    /**
     * 拒绝
     */
    public function orderNo(){
        extract(input());
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $tui = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->field('user_id,order_cancel_status,order_cancel_pay')
            ->find();
        if($tui['order_cancel_status'] != 4){
            return json(['code'=>100,'msg'=>'只有待审核的才可以同意']);
        }
        $param  = [
            'order_cancel_status'=>2,
            'updated_at'=>$today,
        ];
        $res = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->update($param);
        if($res){
            return json(['code'=>200,'msg'=>'成功']);
        }else{
            return json(['code'=>100,'msg'=>'失败']);
        }
    }


    /**
     * 退款申请
     * @return \think\response\Json
     */
    public function orderTuiMoneyBefore(){
        extract(input());
        if(Request::instance()->isPost()){
            $order_id = input('tui_id');
            $today = date('Y-m-d H:i:s');
            $order = Db::table('up_self_order')
                ->where('order_id',$order_id)
                ->field('order_cancel_number,total_price,pay_type,order_no,user_id,order_contract,order_query_id,order_id,order_cancel_status,order_cancel_pay,order_master_status')
                ->find();
            if($order['order_cancel_status'] != 3 || $order['order_cancel_pay'] != 2){
                return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
            }
            if($order['order_master_status'] != 1 && $order['order_master_status'] != 3){
                return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
            }
            $refund_price = round($refund_price,2);
            if($refund_price <= 0 || $refund_price > $order['total_price']){
                return json(['code'=>100,'msg'=>'退款金额不能低于0且不能大于订单金额！']);
            }
            $param  = [
                'order_master_status' => 2,
                'order_cancel_money'=>$refund_price,
                'updated_at' => $today,
            ];
            $last = Db::table('up_self_order')
                ->where('order_id',$order_id)
                ->update($param);
            if($last){
                return json(['code'=>200,'msg'=>'成功']);
            }else{
                return json(['code'=>100,'msg'=>'订单状态修改失败，新刷新重试！']);
            }
        }
        $tui = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->field('user_id,order_cancel_status,order_cancel_pay')
            ->find();
        if($tui['order_cancel_status'] != 3 || $tui['order_cancel_pay'] != 2){
            return '只有同意且未退过款的才可以退款！';
            exit();
        }
        return $this->fetch('ordercancel/ordertuimoney',['tui_id'=>$order_id]);
    }
    /**
     * 已支付订单取消后的数据，需要审核
     */
    public function master(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            $map['is_delete'] = 0;
            $map['order_contract'] = ['<>',3];
            $map['order_master_status'] = 2;
            if(isset($contract)&&$contract!="")
            {
                $map['order_contract'] = $contract;
            }
            if(isset($n_title)&&$n_title!="")
            {
                $map['order_no|name|mobile|express_no|order_cancel_number'] = ['like',"%" . $n_title . "%"];
            }
            if(isset($orderid)&&$orderid!="")
            {
                $map['order_id'] = $orderid;
            }
            if(isset($start) && $start)
            {
                $map['order_cancel_time'] = ['>= time',$start];
            }
            if(isset($end) && $end)
            {
                $map['order_cancel_time'] = ['<= time',$end];
            }
            if(isset($start) && $start && isset($end) && $end)
            {
                $map['order_cancel_time'] = ['between time',[$start,$end]];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'o.*,user_username,user_phone';
            $count = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->count();// 获取总条数
            $lists = Db::table('up_self_order')->alias('o')
                ->join('up_u_user u','o.user_id=u.user_id','LEFT')
                ->where($map)
                ->order('is_pay ASC,is_send ASC,created_at ASC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            //----------------------------------------------------------

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch('ordercancel/master');
    }
    /**
     * 退款
     * @return \think\response\Json
     */
    public function orderTuiMoney(){
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->field('order_cancel_number,total_price,pay_type,order_no,user_id,order_contract,order_query_id,order_id,order_cancel_status,order_cancel_pay,order_cancel_money,order_master_status')
            ->find();
        if($order['order_cancel_status'] != 3 || $order['order_cancel_pay'] != 2 || $order['order_master_status'] != 2){
            return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
        }
        $refund_price = $order['order_cancel_money'];
        if($refund_price <= 0 || $refund_price > $order['total_price']){
            return json(['code'=>100,'msg'=>'退款金额不能低于0且不能大于订单金额！']);
        }
        $param  = [
            'order_cancel_pay' => 3,
            'order_master_status'=>4,
            'updated_at' => $today,
        ];
        $payInfo = [
            'total_price' => $order['total_price'],
            'money' => $refund_price,
            'number' => $order['order_no']
        ];
        $refundNo = $order['order_cancel_number'];
        if($order['pay_type'] == 1){ //微信
            $tuiwx = new \app\admin\controller\Tuiwx();
            $res = $tuiwx->refundWx($payInfo,$refundNo);
        }elseif ($order['pay_type'] == 2){ //支付宝
            $tuiali = new \app\admin\controller\Tuiali();
            $res = $tuiali->refund($payInfo,$refundNo);
        }else{
            $tuiali = new \app\admin\controller\Tuiupacp();
            $res = $tuiali->UpacpTuiKuan($refundNo,$refund_price,$order['order_query_id']);
        }
        if($res['status'] == 200){
            $last = Db::table('up_self_order')
                ->where('order_id',$order_id)
                ->update($param);
            if($last){
                //平台退款
                allInRevenue(2,$refund_price,$order['user_id'],4,$order_id,session('username'),$order_id);
                return json(['code'=>200,'msg'=>'成功']);
            }else{
                return json(['code'=>100,'msg'=>'订单状态修改失败，请联系管理员将订单id为 '.$order_id.' 的订单改为已退款！']);
            }
        }else{
            return json(['code'=>100,'msg'=>$res['msg']]);
        }
    }
    /**
     * 退款拒绝
     * @return \think\response\Json
     */
    public function orderTuiMoneyNo(){
        $order_id = input('id');
        $today = date('Y-m-d H:i:s');
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->field('order_cancel_number,total_price,pay_type,order_no,user_id,order_contract,order_query_id,order_id,order_cancel_status,order_cancel_pay,order_cancel_money,order_master_status')
            ->find();
        if($order['order_cancel_status'] != 3 || $order['order_cancel_pay'] != 2 || $order['order_master_status'] != 2){
            return json(['code'=>100,'msg'=>'只有同意且未退过款的才可以退款']);
        }
        $param  = [
            'order_master_status'=>3,
            'updated_at' => $today,
        ];
        $last = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->update($param);
        if($last){
            return json(['code'=>200,'msg'=>'成功']);
        }else{
            return json(['code'=>100,'msg'=>'订单状态修改失败，新刷新重试']);
        }
    }




    /**
     * 订单详情
     */
    /**
     * 订单详情
     */
    public function orderInfo(){
        $order_id = input('order_id');
        $field = 'o.*,user_username,user_phone';
        $order = Db::table('up_self_order')->alias('o')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->where('order_id',$order_id)
            ->field($field)
            ->find();
        $where = [
            'order_id' => $order_id
        ];
        $good_table = 'up_self_goods';
        if($order['order_contract'] != 1){
            $good_table = 'up_goods';
        }
        $field = 'num,unit_price,goods_info,good_id,good_name,good_thumb,attr_id,th_status,refund_status,detail_id';
        $details = Db::table('up_self_order_detail')->alias('od')
            ->join("$good_table g",'od.goods_id=g.good_id','LEFT')
            ->where($where)
            ->field($field)
            ->select();
        return $this->fetch('ordercancel/orderinfo',['data'=>$order,'goods'=>$details]);
    }


    /**
     * 导出汇总
     * @return \think\response\Json
     */
    public function excelOutOrder()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['order_contract'] = ['<>',3];
        if(isset($contract)&&$contract!="")
        {
            $map['order_contract'] = $contract;
        }
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|order_back_order_id|name|mobile|express_no|order_cancel_number'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($orderid)&&$orderid!="")
        {
            $map['order_id'] = $orderid;
        }
        if(isset($type) && $type){
            $map['order_push_erp'] = $type;
        }
        if(isset($cancelstatus) && $cancelstatus){
            $map['order_cancel_status'] = $cancelstatus;
        }else{
            $map['order_cancel_status'] = ['>=',2];
        }
        if(isset($paystatus) && $paystatus){
            $map['order_cancel_pay'] = $paystatus;
        }
        //专为退款审核查看
        if(isset($order_master_status)&&$order_master_status!="")
        {
            if($order_master_status == 1){
                $map['order_master_status'] = ['in','3,4'];
            }else{
                $map['order_master_status'] = $order_master_status;
            }

        }
        if(isset($start)&&$start!=""&&isset($end)&&$end=="")
        {
            $map['order_cancel_time'] = ['>= time',$start];
        }
        if(isset($end)&&$end!=""&&isset($start)&&$start=="")
        {
            $map['order_cancel_time'] = ['<= time',$end];
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end!="")
        {
            $map['order_cancel_time'] = ['between time',[$start,$end]];
        }
        $field = [
            'order_no','order_contract','order_back_order_id','total_price','express_original_price','all_goods_price',
            'all_good_nums', 'name','mobile','pay_type','pay_time',
            'school_name', 'is_send', 'order_cancel_status','order_cancel_pay','order_cancel_money',
            'new_old','order_cancel_remark'
            ,'order_cancel_time','order_cancel_number','o.updated_at','o.order_push_erp','o.order_cancel_push_erp'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_u_user u', 'o.user_id=u.user_id', 'LEFT')
            ->join('up_school s', 'o.order_school=s.school_erp', 'LEFT')
            ->where($map)
            ->field($field)
            ->select();
        if($data){
            foreach ($data as $k => $v){
                $data[$k]['order_cancel_number'] = date('Y-m-d H:i:s',substr($v['order_cancel_number'],1,10));
                if($v['order_cancel_pay'] != 3) $data[$k]['updated_at'] = '';
            }
            $cellname = [
                '订单号','订单类型', '支付流水号', '总价（含邮费）', '运费', '衣服总价',
                '衣服总数量', '收件人', '收件电话', '支付平台', '支付时间',
                '学校名字', '是否发货', '订单是否取消', '是否已退款（取消了订单的才有）', '退款金额（取消了订单的才有）',
                '新老订单','取消备注'
                ,'创建时间','同意时间','打款时间','原单推送状态','取消推送状态'
            ];
            $status = ['order_contract','pay_type','is_send','order_cancel_status','order_cancel_pay','new_old','order_push_erp','order_cancel_push_erp'];
            $values = [
                'order_contract' => [1 => '自营订单',2 => '增补订单']
                ,'pay_type' => [1 => '微信',2 => '支付宝',3 => '银联']
                ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
                ,'order_cancel_status' => [1 => '未取消',2 => '取消被拒',3 => '已同意取消',4 => '待审核']
                ,'order_cancel_pay' => [1 => '正常',2 => '未打款',3 => '已打款']
                ,'new_old' => [1 => '新APP订单',2 => '旧APP订单']
                , 'order_push_erp' => [1 => '未推送',2 => '已推送',3 => '已推送']
                , 'order_cancel_push_erp' => [1 => '未推送',2 => '已推送',3 => '已推送']
            ];
            $res = exportExcel('orderCancel',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }

    /**
     * 导出明细
     * @return \think\response\Json
     */
    public function excelOutDetail()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['order_contract'] = ['<>',3];
        if(isset($contract)&&$contract!="")
        {
            $map['order_contract'] = $contract;
        }
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|order_back_order_id|name|mobile|express_no|order_cancel_number'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($orderid)&&$orderid!="")
        {
            $map['order_id'] = $orderid;
        }
        if(isset($type) && $type){
            $map['order_push_erp'] = $type;
        }
        if(isset($cancelstatus) && $cancelstatus){
            $map['order_cancel_status'] = $cancelstatus;
        }else{
            $map['order_cancel_status'] = ['>=',2];
        }
        if(isset($paystatus) && $paystatus){
            $map['order_cancel_pay'] = $paystatus;
        }
        //专为退款审核查看
        if(isset($order_master_status)&&$order_master_status!="")
        {
            if($order_master_status == 1){
                $map['order_master_status'] = ['in','3,4'];
            }else{
                $map['order_master_status'] = $order_master_status;
            }

        }
        if(isset($start)&&$start!=""&&isset($end)&&$end=="")
        {
            $map['o.order_cancel_time'] = ['>= time',$start];
        }
        if(isset($end)&&$end!=""&&isset($start)&&$start=="")
        {
            $map['o.order_cancel_time'] = ['<= time',$end];
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end!="")
        {
            $map['o.order_cancel_time'] = ['between time',[$start,$end]];
        }
        $field = [
            'o.order_no','o.order_contract','unit_price','num','attr_id','goods_info',
            'goods_coding_unique','name','mobile', 'pay_type','pay_time',
            'school_name', 'is_send', 'o.new_old', 'o.order_push_erp', 'o.order_cancel_push_erp'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_self_order_detail od','o.order_id=od.order_id','LEFT')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->where($map)
            ->field($field)
            ->select();

        if($data){
            $cellname = [
                '订单号', '订单类型', '单价', '数量', '尺码', '产品信息',
                '唯一条码', '收件人', '收件电话', '支付平台', '支付时间',
                '学校名字', '是否发货', '新老订单','原单推送状态','取消推送状态'
            ];
            $status = ['order_contract','pay_type','is_send','new_old', 'order_push_erp', 'order_cancel_push_erp'];
            $values = [
                'order_contract' => [1 => '自营订单',2 => '增补订单']
                ,'pay_type' => [1 => '微信',2 => '支付宝',3 => '银联']
                ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
                ,'new_old' => [1 => '新APP订单',2 => '旧APP订单']
                , 'order_push_erp' => [1 => '未推送',2 => '已推送',3 => '已推送']
                , 'order_cancel_push_erp' => [1 => '未推送',2 => '已推送',3 => '已推送']
            ];
            $res = exportExcel('orderCancelInfo',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }

}